package com.example.im.ui.fragment

import android.content.Context
import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.Toast
import androidx.recyclerview.widget.LinearLayoutManager
import com.example.im.R
import com.example.im.callback.OnClickRoomListener
import com.example.im.common.Constants
import com.example.im.common.ImApplication
import com.example.im.entity.FriendOrRoom
import com.example.im.mvp.base.BasePresenter
import com.example.im.ui.abstracts.AbstractBaseFragment
import com.example.im.ui.adapter.RoomOwnerAdapter
import com.example.im.utils.JsonUtils
import kotlinx.android.synthetic.main.fragment_room_owner.*
import org.jivesoftware.smackx.muc.Affiliate

class RoomOwnerFragment : AbstractBaseFragment<BasePresenter<*>>(), View.OnClickListener {


    private var adapter: RoomOwnerAdapter? = null

    private var mOnClickRoomListener: OnClickRoomListener? = null

    companion object {
        fun newInstance(owners: ArrayList<FriendOrRoom>): RoomOwnerFragment {
            val bundle = Bundle()
            bundle.putSerializable(Constants.BUNDLE_T0_ROOM_DATA, owners)
            val fragment = RoomOwnerFragment()
            fragment.arguments = bundle
            return fragment
        }
    }

    override fun onAttach(context: Context) {
        super.onAttach(context)
        mOnClickRoomListener = context as OnClickRoomListener
    }

    override val layoutId: Int
        get() = R.layout.fragment_room_owner

    override fun initView() {

        val owners = getOwners()
        val account = ImApplication.appDatabase()
            .accountDao().account()
        val isOwner = owners[0].account == account.username
        if (isOwner)
            tv_room_delete_owner.visibility = View.VISIBLE
        else
            tv_room_delete_owner.visibility = View.GONE

        if (owners.isNotEmpty()) {
            tv_name.text = owners[0].nickname
            owners.removeAt(0)
        }
        if (owners.isEmpty()) {
            tv_room_delete_owner.visibility = View.GONE
        }

        adapter = RoomOwnerAdapter(activity!!, owners, isOwner)
        recycler_view.layoutManager = LinearLayoutManager(activity!!)
        recycler_view.adapter = adapter

        tv_room_delete_owner.setOnClickListener(this)
    }

    override fun initPresenter() {

    }

    override fun initLazyLoad() {

    }

    override fun onClick(v: View?) {
        mOnClickRoomListener!!.onClickUserKick(v!!, adapter!!.getSelectedItem())
    }

    private fun getOwners(): MutableList<FriendOrRoom> {
        val arrayList = arguments!!.getSerializable(Constants.BUNDLE_T0_ROOM_DATA)
                as ArrayList<*>
        val owners = mutableListOf<FriendOrRoom>()
        arrayList.forEach {
            owners.add(it as FriendOrRoom)
        }
        return owners
    }
}